<template>
  <div class="user-list">
    <el-card class="user-card">
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
          <div class="header-actions">
            <el-input
              v-model="searchForm.keyword"
              placeholder="请输入用户名/邮箱/手机号"
              style="width: 300px; margin-right: 10px"
              clearable
              @clear="handleSearch"
              @keydown.enter="handleSearch"
            >
              <template #append>
                <el-button icon="Search" @click="handleSearch" :loading="loading" />
              </template>
            </el-input>
            <el-button type="primary" @click="handleAdd">添加用户</el-button>
          </div>
        </div>
      </template>

      <el-table
        :data="userList"
        v-loading="loading"
        style="width: 100%"
        row-key="id"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="nickname" label="昵称" width="120" />
        <el-table-column prop="email" label="邮箱" width="150" />
        <el-table-column prop="phone" label="手机号" width="120" />
        <el-table-column prop="roleName" label="角色" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastLogin" label="最后登录" width="180" />
        <el-table-column prop="createdAt" label="创建时间" width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button
              size="small"
              :type="scope.row.status === 1 ? 'warning' : 'success'"
              @click="handleToggleStatus(scope.row)"
            >
              {{ scope.row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
              :disabled="scope.row.id === 1"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" :maxlength="50" show-word-limit :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!isEdit">
          <el-input v-model="userForm.password" type="password" :maxlength="32" show-word-limit />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="userForm.nickname" :maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" :maxlength="100" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" :maxlength="11" />
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="userForm.roleId" placeholder="请选择角色" style="width: 100%">
            <el-option
              v-for="role in roleList"
              :key="role.id"
              :label="role.name"
              :value="role.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="isEdit" label="状态" prop="status">
          <el-switch
            v-model="userForm.status"
            :active-value="1"
            :inactive-value="0"
            active-text="正常"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave" :loading="saveLoading">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { UserListItem, CreateUserRequest, UpdateUserRequest } from '@/types/api/user'
import type { Role } from '@/types/api/role'
import { userApi } from '@/api/modules/user'
import { roleApi } from '@/api/modules/role'
import { formUtils } from '@/utils'

// 表格相关
const loading = ref(false)
const userList = ref<UserListItem[]>([])

// 角色列表
const roleList = ref<Role[]>([])

// 搜索表单
const searchForm = reactive({
  keyword: ''
})

// 分页相关
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const saveLoading = ref(false)
const userFormRef = ref()
const currentUserId = ref(0)

// 表单数据
const userForm = reactive({
  username: '',
  password: '',
  nickname: '',
  email: '',
  phone: '',
  roleId: null as number | null,
  status: 1
})

// 表单验证规则
const userRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 50, message: '用户名长度为3-50个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 32, message: '密码长度为6-32个字符', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { max: 50, message: '昵称长度不能超过50个字符', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  roleId: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

// 获取用户列表
const getUserList = async () => {
  loading.value = true
  try {
    const response = await userApi.getUserList({
      page: pagination.page,
      pageSize: pagination.pageSize,
      keyword: searchForm.keyword
    })
    userList.value = response.data.data.list
    pagination.total = response.data.data.total
  } catch (error) {
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 获取角色列表
const getRoleList = async () => {
  try {
    const response = await roleApi.getRoleList()
    roleList.value = response.data.data
  } catch (error) {
    ElMessage.error('获取角色列表失败')
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  getUserList()
}

// 重置搜索
const handleResetSearch = () => {
  searchForm.keyword = ''
  pagination.page = 1
  getUserList()
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  pagination.page = 1
  getUserList()
}

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.page = val
  getUserList()
}

// 添加用户
const handleAdd = () => {
  dialogTitle.value = '添加用户'
  isEdit.value = false
  dialogVisible.value = true
  // 重置表单
  Object.assign(userForm, {
    username: '',
    password: '',
    nickname: '',
    email: '',
    phone: '',
    roleId: null,
    status: 1
  })
}

// 编辑用户
const handleEdit = async (row: UserListItem) => {
  dialogTitle.value = '编辑用户'
  isEdit.value = true
  dialogVisible.value = true
  currentUserId.value = row.id

  try {
    const response = await userApi.getUserDetail(row.id)
    const userData = response.data.data
    Object.assign(userForm, {
      username: userData.username,
      password: '',
      nickname: userData.nickname,
      email: userData.email,
      phone: userData.phone,
      roleId: userData.roleId,
      status: userData.status
    })
  } catch (error) {
    ElMessage.error('获取用户详情失败')
  }
}

// 查看用户详情
const handleView = async (row: UserListItem) => {
  dialogTitle.value = '用户详情'
  isEdit.value = false
  dialogVisible.value = true
  currentUserId.value = row.id

  try {
    const response = await userApi.getUserDetail(row.id)
    const userData = response.data.data
    Object.assign(userForm, {
      username: userData.username,
      password: '',
      nickname: userData.nickname,
      email: userData.email,
      phone: userData.phone,
      roleId: userData.roleId,
      status: userData.status
    })
  } catch (error) {
    ElMessage.error('获取用户详情失败')
  }
}

// 启用/禁用用户
const handleToggleStatus = async (row: UserListItem) => {
  try {
    await userApi.updateUserStatus(row.id, {
      status: row.status === 1 ? 0 : 1
    })
    ElMessage.success(`${row.status === 1 ? '禁用' : '启用'}成功`)
    await getUserList()
  } catch (error) {
    ElMessage.error(`${row.status === 1 ? '禁用' : '启用'}失败`)
  }
}

// 删除用户
const handleDelete = (row: UserListItem) => {
  if (row.id === 1) {
    ElMessage.warning('不能删除超级管理员')
    return
  }

  formUtils.handleDeleteConfirm(`用户 "${row.username}"`, async () => {
    await userApi.deleteUser(row.id)
    getUserList()
  }, {
    successMessage: '删除成功',
    errorMessage: '删除失败'
  })
}

// 保存用户信息
const handleSave = async () => {
  if (!userFormRef.value) return

  await userFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      saveLoading.value = true
      try {
        if (isEdit.value) {
          // 编辑用户
          const updateData: UpdateUserRequest = {
            nickname: userForm.nickname,
            email: userForm.email,
            phone: userForm.phone,
            roleId: userForm.roleId as number
          }
          await userApi.updateUser(currentUserId.value, updateData)
          ElMessage.success('更新成功')
        } else {
          // 添加用户
          const createData: CreateUserRequest = {
            username: userForm.username,
            password: userForm.password,
            nickname: userForm.nickname,
            email: userForm.email,
            phone: userForm.phone,
            roleId: userForm.roleId as number
          }
          await userApi.createUser(createData)
          ElMessage.success('添加成功')
        }
        dialogVisible.value = false
        await getUserList()
      } catch (error: any) {
        ElMessage.error(error.message || (isEdit.value ? '更新失败' : '添加失败'))
      } finally {
        saveLoading.value = false
      }
    }
  })
}

// 对话框关闭
const handleDialogClose = () => {
  formUtils.resetForm(userFormRef.value, userForm, {
    username: '',
    password: '',
    nickname: '',
    email: '',
    phone: '',
    roleId: null,
    status: 1
  })
}

// 初始化
onMounted(() => {
  getUserList()
  getRoleList()
})
</script>

<style scoped lang="scss">
.user-list {
  .user-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>
